package com.example.shellshopping;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;

import com.example.shellshopping.goods.GoodsTypeFragment;
import com.example.shellshopping.goods.TypeAdapter;
import com.example.shellshopping.goods.TypeBean;
import com.example.shellshopping.newLayout.HorizontalListView;
import com.example.shellshopping.utils.BaseFragment;
import com.example.shellshopping.utils.URLUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

/**
 * 类型的碎片
 */
public class TypeFragment extends BaseFragment {
    HorizontalListView typeLV;
    EditText searchET;
    List<TypeBean.DataBean> data;  //数据源
    private TypeAdapter adapter;
    private FragmentManager fm;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_type, container, false);
        initView(view);
        fm = getChildFragmentManager();
        //确定数据源
        data = new ArrayList<>();
        //设置适配器
        adapter = new TypeAdapter(getContext(),data);
        typeLV.setAdapter(adapter);
        getNetwork(URLUtils.queryAllCategory_url);
        //设置点击事件
        setListener();
        return view;
    }

    //点击上侧的item切换右侧的页面
    private void changeRightPage(int postion){
        TypeBean.DataBean dataBean = data.get(postion);  //得到切换的数据
        int id = dataBean.getId();
        FragmentTransaction transaction = fm.beginTransaction();
        GoodsTypeFragment gtfrag = GoodsTypeFragment.newInstance(id + "", "");
        transaction.replace(R.id.frag_type_layout,gtfrag);
        transaction.commit();
    }

    private void setListener() {
        typeLV.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                adapter.setClickPos(position);
                changeRightPage(position);
            }
        });
    }

    @Override
    public void onSuccess(String result){
        super.onSuccess(result);
        TypeBean typeBean = new Gson().fromJson(result,TypeBean.class);//解析数据
        List<TypeBean.DataBean> list = typeBean.getData();//获取网络集合
        data.addAll(list);//将网络数据添加到list view的数据源当中
        adapter.notifyDataSetChanged();//提示更新
        changeRightPage(0);
    }

    private void initView(View view) {
        typeLV = view.findViewById(R.id.frag_type_lv);
        searchET = view.findViewById(R.id.frag_type_et);
    }
}